<template>
	<el-dialog v-model="currentVisible" :class="$style['dialog-audio']" :title="title" :close-on-click-modal="false"
		:close-on-press-escape="false" @closed="handleCloseDialog">
		<el-form :model="ttsFormData" ref="refTTSForm" label-width="150px" :rules="ttsRules">
			<el-form-item label="选择广播服务器">
				<el-select v-model="serviceID" placeholder="选择广播服务器" @change="handleChangeService">
					<template :key="item.device_id" v-for="item in serviceOptions">
						<el-option :label="item.device_name" :value="item.device_id" />
					</template>
				</el-select>
			</el-form-item>

			<el-form-item prop="TTSEngineName" label="选择 TTS 引擎">
				<el-select v-model="ttsFormData.TTSEngineName" placeholder="选择引擎">
					<template :key="item.name" v-for="item in TTSEngineOptions">
						<el-option :label="item.name" :value="item.name" />
					</template>
				</el-select>
			</el-form-item>
			<el-form-item label="播放语速">
				<el-input :class="$style['tts-form-input']" v-model="ttsFormData.TTSSpeed" type="number"
					placeholder="播放语速" />
			</el-form-item>
			<el-form-item label="重复次数">
				<el-input :class="$style['tts-form-input']" v-model="ttsFormData.RepeatTime" type="number"
					placeholder="重复次数" />
			</el-form-item>
			<el-form-item prop="text" label="设置播放的文本内容">
				<el-input :class="$style['tts-form-input']" v-model="ttsFormData.text" type="textarea" :row="5"
					placeholder="请输入需要播报的文本内容" />
			</el-form-item>
		</el-form>

		<h6 :class="$style['required-title']">选择播放终端设备</h6>
		<el-input v-model="terminalKeyword" placeholder="请输入需要筛选的终端设备" clearable @input="handleFilterTerminal">
			<template #prefix>
				<el-icon class="el-input__icon">
					<Search />
				</el-icon>
			</template>
		</el-input>

		<!-- <el-checkbox-group v-model="terminalID" :class="$style['terminal-checkbox-group']">
			<template :key="item.name" v-for="item in terminalOptions">
				<el-checkbox :value="item.endpointId" :label="item.device_name" />
			</template>
		</el-checkbox-group> -->
		<el-tree :class="$style['terminal-checkbox-group']" v-model="terminalID" node-key="device_id"
			:default-checked-keys="device_id" :data="terminalOptions" :props="terminalProps" show-checkbox
			:check-strictly="true" empty-text="暂无可播放的终端" @check="handleTerminalChange">
		</el-tree>

		<div :class="$style['dialog-button-wrapper']">
			<el-button @click="handleCloseDialog">取消</el-button>
			<el-button type="primary" :loading="loading" :disabled="!terminalID.length"
				@click="playAudio">播放</el-button>
		</div>
	</el-dialog>
</template>

<script>
import { ref, watch, onBeforeUnmount } from 'vue'
import VueTypes from 'vue-types'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

import http from '@/utils/http'
import { filterListData } from '@/utils/tools'

export default {
	name: 'dialog-play-audio-tts',
	components: {
		Search
	},
	props: {
		modelValue: VueTypes.bool.def(false),
		title: VueTypes.string.def('TTS 播放')
	},
	emits: ['update:value', 'complete'],
	setup(props, { emit }) {
		const refAudioDialog = ref(null)
		const refTTSForm = ref(null)
		const loading = ref(false)
		const currentVisible = ref(false)
		const serviceID = ref('')
		const serviceOptions = ref([])
		const TTSEngineOptions = ref([])
		const ttsFormData = ref({
			text: '',
			TTSEngineName: '',
			TTSSpeed: 5,
			RepeatTime: 3
		})
		const terminalProps = {
			children: 'children',
			label: 'device_name',
			id: 'device_id'
		}
		const terminalKeyword = ref('')
		const terminalID = ref([])
		const terminalOptions = ref([])

		const ttsRules = {
			//定义验证规则，有两种方式：
			//1.使用ele原生的验证规则。
			TTSEngineName: [{ required: true, message: '请选择 TTS 引擎', trigger: 'blur' }],
			text: [{ required: true, message: '请输入需要播报的文本内容', trigger: 'blur' }]
		}

		let filterKeyword = filterListData()
		const device_id = ref([])
		const open = (data = {}) => {
			switch (data.node_id) {
				// 广播服务器
				case 24:
					serviceID.value = data.id
					break
				// 广播终端
				case 25:
					serviceID.value = data.parent_id
					device_id.value = [data.device_id]
					break
				default:
					break
			}

			getService()
			getTTSEngine()

			currentVisible.value = true
		}

		const getService = () => {
			http.get('/v1/broadcast/getServer', {}).then(res => {
				if (res.code == 1) {
					serviceOptions.value = Array.isArray(res.data) ? res.data : []

					// 预设的服务器 ID 不在列表中的情况是，选中第一个选项
					if (!serviceOptions.value.find(item => item.device_id === serviceID.value)) {
						serviceID.value = serviceOptions.value[0].device_id
					}

					if (serviceID.value) {
						handleChangeService(serviceID.value)
					}
				}
			})
		}

		const getTTSEngine = () => {
			http.get('/v1/broadcast/getTTSEngine', {}).then(res => {
				if (res.code == 1) {
					TTSEngineOptions.value = res.data

					ttsFormData.value.TTSEngineName = TTSEngineOptions.value[0].name
				}
			})
		}

		const getTerminal = (id) => {
			http.get('/v1/broadcast/terminal', { params: { device_id: id } }).then(res => {
				if (res.code == 1) {
					terminalOptions.value = res.data
					if (device_id.value.length > 0) {
						terminalOptions.value.forEach(item => {
							if (device_id.value.includes(item.device_id)) {
								terminalID.value.push(item)
							}
						})
					}
					filterKeyword.setData(res.data)
				}
			})
		}

		const handleChangeService = (value) => {
			getTerminal(value)
		}

		const handleFilterTerminal = (value) => {
			terminalOptions.value = filterKeyword.filter(value, 'device_name')
		}
		const handleTerminalChange = (data, checked, indeterminate) => {
			terminalID.value = checked.checkedNodes
		}
		const playAudio = () => {
			refTTSForm.value.validate(valid => {
				if (valid) {
					const postData = {
						...ttsFormData.value,
						endpointIds: terminalID.value,
						serverIp: '',
						url: ''
					}

					const currentService = serviceOptions.value.find(item => item.device_id === serviceID.value)

					if (currentService) {
						postData.serverIp = currentService.ip
						postData.url = currentService.url
					}

					loading.value = true

					http.post('/v2/broadcast/playTTS', postData).then(res => {
						if (res.code == 1) {
							ElMessage.success('处理成功')
							handleCloseDialog()
							emit('complete')
						}

						loading.value = false
					}).catch(() => {
						loading.value = false
					})
				}
			})
		}

		const handleCloseDialog = () => {
			currentVisible.value = false
			serviceOptions.value = []
			TTSEngineOptions.value = []
			terminalOptions.value = []
			serviceID.value = ''
			ttsFormData.value = {
				text: '',
				TTSEngineName: ''
			}
			terminalID.value = []
			refTTSForm.value.resetFields()

			emit('update:value', false)
		}

		watch(
			() => props.modelValue,
			visible => {
				currentVisible.value = visible
			}
		)

		onBeforeUnmount(() => {
			currentVisible.value = false
			filterKeyword.destroy()

			filterKeyword = null
		})

		return {
			refAudioDialog,
			refTTSForm,
			currentVisible,
			loading,
			ttsRules,
			serviceOptions,
			terminalOptions,
			serviceID,
			ttsFormData,
			terminalID,
			terminalKeyword,
			TTSEngineOptions,
			handleChangeService,
			handleFilterTerminal,
			handleCloseDialog,
			playAudio,
			open,
			terminalProps,
			handleTerminalChange,
			device_id
		}
	}
}
</script>

<style lang="scss" module>
.dialog-audio {
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	max-width: 600px;
	height: calc(100vh - 20vh);
	max-height: 800px;
	margin: 10vh auto 0;

	& [class~="el-dialog__body"] {
		box-sizing: border-box;
		flex: 1 0 0;
		display: flex;
		flex-direction: column;
		gap: 10px;
		width: 100%;
		height: 0;
		padding: 20px 0 0 0;
	}

	& [class~="el-dialog__header"] {
		padding-bottom: 0;
	}
}

.sub-title {
	height: 20px;
	line-height: 20px;
	font-size: 12px;
	font-weight: 400;
	color: #888;
}

.service-select-wrapper {
	display: flex;
	align-items: center;
	gap: 10px;

	& dt {
		flex: 140px 0 0;
	}

	& dd {
		flex: 1;
	}
}

.tts-form-input {
	& [class~="el-textarea__inner"] {
		height: 100px;
	}
}

.required-title {
	&:before {
		content: "*";
		margin-right: 4px;
		color: #F56C6C;
	}
}

.terminal-checkbox-group {
	overflow: auto;
	display: block;
	box-sizing: border-box;
	flex: 1 0 0;
	height: 0;
	padding: 12px;
	background-color: #FFF;
	border-radius: 5px;
	scrollbar-width: thin;
	scrollbar-color: rgba(0, 0, 0, 0.3) transparent;

	&::-webkit-scrollbar {
		width: 5px;
	}

	&::-webkit-scrollbar-track {
		-webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.3);
		border-radius: 10px;
	}

	&::-webkit-scrollbar-thumb {
		background-color: rgba(0, 0, 0, 0.2);
		border-radius: 3px;
	}
}

.dialog-button-wrapper {
	display: flex;
	justify-content: center;
	margin-top: 12px;

	& [class~="el-button"] {
		width: 100px;
	}
}
</style>
